public async Task <IActionResult> OnGetCallbackAsync(string userAgent, string returnUrl = null, string remoteError = null)
        {
            //用于判断请求浏览器类型
            userAgent = Request.Headers["User-Agent"];
            UserAgent.UserAgent ua = new UserAgent.UserAgent(userAgent);

            returnUrl = returnUrl ?? Url.Content("~/");
            if (remoteError != null)
            {
                ErrorMessage = $"Error from external provider: {remoteError}";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            // Sign in the user with this external login provider if the user already has a login.
            var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (result.Succeeded)
            {
                _logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Identity.Name, info.LoginProvider);
                //return LocalRedirect("~/Home/ExternalLoginSuceed");  //go to page that can automatically close current child window
                //return LocalRedirect(returnUrl);

                //用于判断请求浏览器类型
                if ((b.IsMatch(userAgent) || v.IsMatch(userAgent.Substring(0, 4))))
                {
                    //return LocalRedirect("~/Home/ExternalLoginSuceed");  //go to page that can automatically close current child window
                    return(LocalRedirect(returnUrl));
                }
                else
                {
                    return(LocalRedirect("~/Home/ExternalLoginSuceed"));  //go to page that can automatically close current child window
                }
            }
            if (result.IsLockedOut)
            {
                return(RedirectToPage("./Lockout"));
            }
            else
            {
                // If the user does not have an account, then ask the user to create an account.
                ReturnUrl     = returnUrl;
                LoginProvider = info.LoginProvider;
                if (info.Principal.HasClaim(c => c.Type == ClaimTypes.Email))
                {
                    Input = new InputModel
                    {
                        Email = info.Principal.FindFirstValue(ClaimTypes.Email)
                    };
                }
                return(Page());
            }
        }
        public async Task <IActionResult> OnPostConfirmationAsync(string userAgent, string returnUrl = null)
        {
            userAgent = Request.Headers["User-Agent"];
            UserAgent.UserAgent ua = new UserAgent.UserAgent(userAgent);

            returnUrl = returnUrl ?? Url.Content("~/");
            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information during confirmation.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            if (ModelState.IsValid)
            {
                var user = new IdentityUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
                        //return LocalRedirect(returnUrl);
                        //return LocalRedirect("~/Home/ExternalLoginSuceed");  //go to page that can automatically close current child window

                        //判断如果是手机浏览器则将子窗口关闭
                        if ((b.IsMatch(userAgent) || v.IsMatch(userAgent.Substring(0, 4))))
                        {
                            //return LocalRedirect("~/Home/ExternalLoginSuceed");  //go to page that can automatically close current child window
                            return(LocalRedirect(returnUrl));
                        }
                        else
                        {
                            //return LocalRedirect(returnUrl);
                            return(LocalRedirect("~/Home/ExternalLoginSuceed"));
                        }
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(Page());
        }
Example #3
0
        public async Task <IActionResult> Index(string userAgent)
        {
            await _emailSender.SendEmailAsync(
                "*****@*****.**",
                "Visit alert!",
                $"Some one open your dreamflights");

            //get the cookie values and put into viewbags
            //把cookie的值放入页面
            ViewBag.FromCityName = _cookieControl.Get("FromCityName");
            ViewBag.ToCityName   = _cookieControl.Get("ToCityName");
            if (_cookieControl.Get("FromCityID") != null && _cookieControl.Get("ToCityID") != null)
            {
                ViewBag.FromCityID = int.Parse(_cookieControl.Get("FromCityID"));
                ViewBag.ToCityID   = int.Parse(_cookieControl.Get("ToCityID"));
            }
            ViewBag.adults   = _cookieControl.Get("adults");
            ViewBag.youths   = _cookieControl.Get("youths");
            ViewBag.children = _cookieControl.Get("children");
            ViewBag.cabin    = _cookieControl.Get("cabin");

            //if TempData["SessionTimeout"] has value, which means session has timed out, then display "session timed out" in the main page
            //如果session过期就返回主页,并以TempData["SessionTimeout"]作为session过期的信号
            if (TempData["SessionTimeout"] != null)
            {
                ViewBag.SessionTimeout = TempData["SessionTimeout"].ToString();
            }

            //用于登陆的panel
            ExternalLogins         = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            ViewBag.ExternalLogins = ExternalLogins;

            //用于登陆的panel
            string returnUrl = null;

            returnUrl         = returnUrl ?? Url.Content("~/");
            ViewBag.ReturnUrl = returnUrl;

            //detect the brower type and redirect to the corresponding view
            userAgent = Request.Headers["User-Agent"];
            UserAgent.UserAgent ua = new UserAgent.UserAgent(userAgent);
            ViewBag.userAgent = ua.Browser.IsMobileDevice.ToString();
            if ((b.IsMatch(userAgent) || v.IsMatch(userAgent.Substring(0, 4))))
            {
                return(View("IndexMobile"));
            }
            else
            {
                return(View());
            }
        }
        public async Task <IActionResult> OnPostAsync(string userAgent, string returnUrl = null)
        {
            //用于判断请求浏览器类型
            userAgent = Request.Headers["User-Agent"];
            UserAgent.UserAgent ua = new UserAgent.UserAgent(userAgent);

            returnUrl = returnUrl ?? Url.Content("~/");

            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure : true);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");
                    //return LocalRedirect(returnUrl);
                    //return LocalRedirect("~/Home/ExternalLoginSuceed");  //go to page that can automatically close current child window

                    //用于判断请求浏览器类型
                    if ((b.IsMatch(userAgent) || v.IsMatch(userAgent.Substring(0, 4))))
                    {
                        return(LocalRedirect(returnUrl));
                    }
                    else
                    {
                        return(LocalRedirect(returnUrl));
                        //return LocalRedirect("~/Home/ExternalLoginSuceed");
                    }
                }
                if (result.RequiresTwoFactor)
                {
                    return(RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe }));
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return(RedirectToPage("./Lockout"));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return(Page());
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Example #5
0
        public BrowserData(IHttpContextAccessor ctx, IAgriConfigurationRepository sd)
        {
            _ctx = ctx;
            _sd  = sd;

            try
            {
                UserAgent.UserAgent ua = new UserAgent.UserAgent(_ctx.HttpContext.Request.Headers["User-Agent"]);
                BrowserName    = ua.Browser.Name;
                BrowserVersion = ua.Browser.Version;
                BrowserOs      = ua.OS.Name;
                BrowserAgent   = _ctx.HttpContext.Request.Headers["User-Agent"].ToString();

                var ab      = _sd.GetAllowableBrowsers();
                var browser = ab.Where(a => a.Name.Equals(BrowserName, StringComparison.CurrentCultureIgnoreCase))
                              .SingleOrDefault();         //known.FindIndex(r => r.name == BrowserName);
                if (BrowserOs == "iOS")
                {
                    OSValid = false;
                }
                else
                {
                    OSValid = true;
                    if (browser == null)
                    {
                        BrowserValid = false;
                        BrowserName  = "Unknown";
                    }
                    else
                    {
                        BrowserValid = true;
                        var minVer  = Version.Parse(browser.MinVersion);
                        var thisVer = Version.Parse(BrowserVersion);
                        if (thisVer < minVer)
                        {
                            BrowserOutofdate = true;
                        }
                        else
                        {
                            BrowserOutofdate = false;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                BrowserName = "Unknown";
                throw new Exception("Could not retrieve browser type.!", ex);
            }
        }
Example #6
0
        public BrowserData(IHttpContextAccessor ctx, StaticData sd)
        {
            _ctx = ctx;
            _sd  = sd;

            try
            {
                UserAgent.UserAgent ua = new UserAgent.UserAgent(_ctx.HttpContext.Request.Headers["User-Agent"]);
                BrowserName    = ua.Browser.Name;
                BrowserVersion = ua.Browser.Version;
                BrowserOs      = ua.OS.Name;
                BrowserAgent   = _ctx.HttpContext.Request.Headers["User-Agent"].ToString();

                Models.StaticData.Browsers ab = _sd.GetAllowableBrowsers();
                int indx = ab.known.FindIndex(r => r.name == BrowserName);
                if (BrowserOs == "iOS")
                {
                    OSValid = false;
                }
                else
                {
                    OSValid = true;
                    if (indx < 0)
                    {
                        BrowserValid = false;
                        BrowserName  = "Unknown";
                    }
                    else
                    {
                        BrowserValid = true;
                        var minVer  = Version.Parse(ab.known[indx].minVersion);
                        var thisVer = Version.Parse(BrowserVersion);
                        if (thisVer < minVer)
                        {
                            BrowserOutofdate = true;
                        }
                        else
                        {
                            BrowserOutofdate = false;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                BrowserName = "Unknown";
                throw new Exception("Could not retrieve browser type.!");
            }
        }
Example #7
0
        // GET: /<controller>/
        public ActionResult Index(string userAgent)
        {
            if (string.IsNullOrEmpty(userAgent))
            {
                userAgent = Request.Headers["User-Agent"];
            }

            ViewBag.userAgent = userAgent;

            UserAgent.UserAgent ua = new UserAgent.UserAgent(userAgent);

            var aa = ua.Browser;

            return(View(ua));
        }
        public UserAgent.UserAgent BrowserLookup()
        {
            string userAgent = "";

            if (string.IsNullOrEmpty(userAgent))
            {
                userAgent = Request.Headers["User-Agent"];
            }

            ViewBag.userAgent = userAgent;

            UserAgent.UserAgent ua = new UserAgent.UserAgent(userAgent);

            var aa = ua.Browser;

            return(ua);
            //return View(ua);
        }
Example #9
0
        private Login GetLogin(bool canILogin, User user)
        {
            var login     = new Login();
            var userAgent = Request.Headers["User-Agent"];

            UserAgent.UserAgent ua = new UserAgent.UserAgent(userAgent);
            login.BrowserId      = ua.Browser.BrowserCode;
            login.BrowserVersion = ua.Browser.Version;
            login.BrowserTitle   = ua.Browser.Name;
            login.Id             = Guid.NewGuid();
            login.LoginIP        = HttpContext.Features.Get <IHttpConnectionFeature>()?.RemoteIpAddress?.ToString();
            login.LoginTimespan  = DateTimeOffset.UtcNow;
            login.User           = user;
            login.OsVersion      = ua.OS.Version;
            login.OsTitle        = ua.OS.Name;
            login.WasSuccessful  = canILogin;

            return(login);
        }
        public IActionResult Post([FromBody] ViewModels.ParticipantViewModel Participantvalues)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            CertifiedVals = ScoreValLogic.Certify(Participantvalues);
            GeoLocProps GetGeoLocation = getGeoLocations().Result;
            string      Address        = string.Format("{0} {1} {2}", Participantvalues.City, " , ", Participantvalues.State);
            MapPoint    mapCords       = latlangofAddr(Address, GetGeoLocation.Latitude, GetGeoLocation.Longitude);
            bool        ZipCordsMatch  = VerifyZipCords(GetGeoLocation.ZipCode, Participantvalues.Zip);

            scoremodel = CalculateScore.CalscoreVal(CertifiedVals, mapCords, ZipCordsMatch);
            UserAgent.UserAgent ua = BrowserLookup();



            storetoDB(Participantvalues, scoremodel, GetGeoLocation, ua, mapCords);
            return(Ok());
        }
Example #11
0
        public JsonResult GetSessionInfo()
        {
            var response = new SessionInfoResponse();

            var userAgent = HttpContext.Request.Headers["User-Agent"].ToString();

            var userAgentModel = new UserAgent.UserAgent(userAgent);

            var sessionRequest = new SessionRequest()
            {
                Type    = 1,
                Browser = new Browser
                {
                    Name    = userAgentModel.Browser.Name,
                    Version = userAgentModel.Browser.Version
                },
                Connection = new Connection
                {
                    IpAddress = HttpContext.Connection.RemoteIpAddress.ToString(),
                    Port      = HttpContext.Connection.RemotePort
                }
            };

            var sessionInfo = _sessionManager.GetSessionInfo(sessionRequest);

            response.Success = sessionInfo.Status == ResponseStatus.Success;

            if (sessionInfo.Status == ResponseStatus.Success)
            {
                response.DeviceId  = sessionInfo.Data.DeviceId;
                response.SessionId = sessionInfo.Data.SessionId;
            }
            else if (sessionInfo.DisplayMessage)
            {
                response.Message = sessionInfo.Message;
            }

            return(Json(response));
        }
        //-------------------------------------------------------------------------------------------------------------------------



        //--------------------------------------------------------------------------------------------------------------------------

        public void storetoDB(ViewModels.ParticipantViewModel Participantvalues, ScoreModel score, GeoLocProps geo, UserAgent.UserAgent useragent, MapPoint mapCoords)
        {
            ParticipantDBViewModel dbModel = CertifyParticipant.storingtoDB(Participantvalues, score, geo, useragent, mapCoords);

            Participant participant = Mapper.Map <Participant>(dbModel);


            SurveyOptionsDBModel surveymodel = CalculateScore.getthesurveyObject();

            DAL.Models.Survey surveydal = new DAL.Models.Survey();
            //defining the survey object
            surveydal.Survey_Name       = surveymodel.Survey_Name;
            surveydal.Survey_Active     = surveymodel.Survey_Active;
            surveydal.SurveyId          = surveymodel.SurveyId;
            surveydal.CalAddressScore   = surveymodel.CalAddressScore;
            surveydal.CalAgeScore       = surveymodel.CalAgeScore;
            surveydal.CalSocialScore    = surveymodel.CalSocialScore;
            surveydal.CalTwoFactorScore = surveymodel.CalTwoFactorScore;

            _unitOfWork.ParticipantRepository.InsertSurveyParticipant(participant);

            _unitOfWork.ParticipantRepository.InsertSurveyParticipantTable(participant, surveydal);
        }
        public async Task Invoke(HttpContext context)
        {
            var statisticsContext = context.RequestServices.GetRequiredService <StatisticsAppDbContext>();

            //var statisticsContext = context.RequestServices.CreateScope().ServiceProvider.GetRequiredService<StatisticsAppDbContext>();
            //var httpRequestInfo = context.RequestServices.GetRequiredService<IHttpRequestInfoService>();

            if (
                !context.Request.IsAjaxRequest() &&
                (context.Request.Path.Value.Equals("/") || context.Request.Path.Value.StartsWith("/Details"))
                )
            //if (!context.Request.IsAjaxRequest()
            //		&& (!context.Request.Path.Value.StartsWith("/RenderOpenSearch"))
            //		&& (!conte|xt.Request.Path.Value.StartsWith("/AdminProfile"))
            //)
            {
                //var userIp = GetCurrentIpAddress(context);
                //var now = DateTime.Now;
                //var st = statisticsContext.Statistics.Where(c => c.IpAddress.Equals(userIp));
                //var temp = await st.FirstOrDefaultAsync(c => c.CreateDate.Year == now.Year && c.CreateDate.Month == now.Month && c.CreateDate.Day == now.Day);

                //if (temp != null)
                //{
                //	temp.Count++;
                //	temp.ModifyDate = DateTime.Now;
                //	statisticsContext.Entry(temp).Property(x => x.Count).IsModified = true;
                //	statisticsContext.Entry(temp).Property(x => x.ModifyDate).IsModified = true;
                //	//statisticsContext.Statistics.Update(temp);
                //	await statisticsContext.SaveChangesAsync();
                //}
                //else
                //{
                //	var request = context.Request;
                //	var ref1 = httpRequestInfo.GetReferrerUri();
                //	var referer = httpRequestInfo.GetReferrerUrl();
                //	var acLang = request.Headers["Accept-Language"];
                //	var header = request.Headers["User-Agent"];
                //	var userAgent = new UserAgent.UserAgent(header);

                //	//var routeValues = context.ActionDescriptor.RouteValues;
                //	//var controllerName = routeValues["Controller"];
                //	//var actionName = routeValues["Action"];
                //	//var pageName = routeValues["Page"];
                //	//var areaName = routeValues["Area"];

                //	var s = new Offishopp.Core.Domain.Entities.Statistics()
                //	{
                //		Count = 1,
                //		CreateDate = DateTime.Now,
                //		ModifyDate = DateTime.Now,
                //		Browser = userAgent.Browser.Name,
                //		Os = userAgent.Os.Name,
                //		UserAgent = header.ToString(),
                //		AcceptLanguage = acLang.ToString(),
                //		Host = request.Host.ToString(),
                //		IsHTTPS = request.IsHttps.ToString(),
                //		Method = request.Method,
                //		Path = request.Path,
                //		Protocol = request.Protocol,
                //		Scheme = request.Scheme,
                //		Referer = referer
                //	};
                //	if (context.User.Identity.IsAuthenticated)
                //	{
                //		s.UserId = context.User.GetUserId();
                //		s.IpAddress = userIp;
                //	}
                //	else
                //	{
                //		s.UserId = "NotSignIn";
                //		s.IpAddress = userIp;
                //	}
                //	await statisticsContext.Statistics.AddAsync(s);
                //	await statisticsContext.SaveChangesAsync();
                //}

                try
                {
                    //var hri = context;
                    //var s1 = hri.GetReferrerUri();
                    //var s12 = hri.GetReferrerUrl();
                    //var s121 = hri.GetRawUri();
                    //var s1211 = hri.GetRawUrl();
                    //var s12111 = hri.GetUserAgent();
                    //var s121111 = hri.GetUrlHelper();
                    //var s1211111 = hri.GetBaseUri();
                    //var s121111111 = hri.GetBaseUrl();
                    //var s1121111111 = hri.ReadRequestBodyAsStringAsync();
                    //var s11211111211 = hri.GetIP();

                    var referer   = context.GetHeaderValue("Referer");
                    var userIp    = GetCurrentIpAddress(context);
                    var request   = context.Request;
                    var acLang    = request.Headers["Accept-Language"];
                    var header    = request.Headers["User-Agent"];
                    var userAgent = new UserAgent.UserAgent(header);

                    var s = new Offishopp.Core.Domain.Entities.Statistics()
                    {
                        Count          = 1,
                        CreateDate     = DateTime.Now,
                        ModifyDate     = DateTime.Now,
                        Browser        = userAgent.Browser.Name,
                        Os             = userAgent.Os.Name,
                        UserAgent      = header.ToString(),
                        AcceptLanguage = acLang.ToString(),
                        Host           = request.Host.ToString(),
                        IsHTTPS        = request.IsHttps.ToString(),
                        Method         = request.Method,
                        Path           = request.Path,
                        Protocol       = request.Protocol,
                        Scheme         = request.Scheme,
                        Referer        = referer
                    };
                    if (context.User.Identity.IsAuthenticated)
                    {
                        s.UserId    = context.User.GetUserId();
                        s.IpAddress = userIp;
                    }
                    else
                    {
                        s.UserId    = "NotSignIn";
                        s.IpAddress = userIp;
                    }
                    await statisticsContext.Statistics.AddAsync(s);

                    await statisticsContext.SaveChangesAsync();
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message, ex.InnerException);
                }
                finally
                {
                    statisticsContext.Dispose();
                }
            }
            await _next.Invoke(context);
        }
Example #14
0
        public static ParticipantDBViewModel storingtoDB(ParticipantViewModel Participantvalues, ScoreModel score, GeoLocProps geo, UserAgent.UserAgent useragent, MapPoint mapCords)
        {
            ParticipantDBViewModel dbModel = new ParticipantDBViewModel();

            dbModel.Age                    = Participantvalues.Age;
            dbModel.AgeValid               = score.AgeValid;
            dbModel.City                   = Participantvalues.City;
            dbModel.CityValid              = score.CityValid;
            dbModel.Date_of_Birth          = DateTime.Parse(Participantvalues.MonthofBirth + "/" + Participantvalues.YearofBirth);
            dbModel.EmailAddress           = Participantvalues.EmailAddress;
            dbModel.FirstName              = Participantvalues.FirstName;
            dbModel.FirstName_Match        = score.FirstName_Match;
            dbModel.LastName               = Participantvalues.LastName;
            dbModel.LastName_Match         = score.LastName_Match;
            dbModel.cords_IpAddrMatch      = score.Coordinates_Match;
            dbModel.OtherGenderType        = Participantvalues.othergender;
            dbModel.GenderIdentity         = Participantvalues.GenderIdentity;
            dbModel.OtherSexualOrientation = Participantvalues.otherSex;
            dbModel.OtherRace              = Participantvalues.OtherRace;
            dbModel.Password               = "";
            dbModel.Hispanic               = Participantvalues.Hispanic;
            dbModel.PhoneNumber            = Participantvalues.PhoneNumber;
            dbModel.Race                   = Participantvalues.Race;
            dbModel.SexualOrientation      = Participantvalues.SexualOrientation;
            dbModel.State                  = Participantvalues.State;
            dbModel.StateValid             = score.StateValid;
            dbModel.Verified               = score.Verified;
            dbModel.Zip                    = Participantvalues.Zip;
            dbModel.geo_IP                 = geo.IP;
            dbModel.geo_City               = geo.City;
            dbModel.geo_CountryName        = geo.CountryName;
            dbModel.geo_RegionName         = geo.RegionName;
            dbModel.geo_ZipCode            = geo.ZipCode;
            dbModel.geo_lattude            = geo.Latitude;
            dbModel.geo_longitude          = geo.Longitude;
            dbModel.OS      = useragent.OS.Name.ToString();
            dbModel.Browser = useragent.Browser.Name.ToString();

            dbModel.AddrLatitude  = mapCords.Latitude;
            dbModel.AddrLongitude = mapCords.Longitude;
            dbModel.latlangMatch  = mapCords.MatchCords;

            dbModel.FinalScaoreVal = score.FinalScaoreVal;
            dbModel.TwoFactorScore = score.TwoFactorScore;
            dbModel.SocialScore    = score.SocialScore;
            dbModel.AgeScore       = score.AgeScore;
            dbModel.AddressScore   = score.AddressScore;
            dbModel.RegisterDate   = DateTime.Now.ToString("U");
            return(dbModel);
        }
Example #15
0
        //process the time data submited from the time slider in the "Search" view, and filter out unwanted fight ticket according the time data.
        public IActionResult FilterForm(string userAgent, int timeEarliestFromDepart, int timeLatiestFromDepart, int timeEarliestToDepart, int timeLatiestToDepart, int timeEarliestFromArrive, int timeLatiestFromArrive, int timeEarliestToArrive, int timeLatiestToArrive, int stops0, int stops1, int stops2)
        {
            ViewBag.stops0 = stops0;
            ViewBag.stops1 = stops1;
            ViewBag.stops2 = stops2;

            //set the slider value after refreshing view
            //设置页面刷新后slider的值(<input id="timeEarliestFromDepart" name="timeEarliestFromDepart" value="@ViewBag.timeEarliestFromDepart">)(values: [$("#timeEarliestFromDepart").val(), $("#timeLatiestFromDepart").val()],)
            ViewBag.timeEarliestFromDepart = timeEarliestFromDepart;
            ViewBag.timeLatiestFromDepart  = timeLatiestFromDepart;
            ViewBag.timeEarliestFromArrive = timeEarliestFromArrive;
            ViewBag.timeLatiestFromArrive  = timeLatiestFromArrive;
            ViewBag.timeEarliestToDepart   = timeEarliestToDepart;
            ViewBag.timeLatiestToDepart    = timeLatiestToDepart;
            ViewBag.timeEarliestToArrive   = timeEarliestToArrive;
            ViewBag.timeLatiestToArrive    = timeLatiestToArrive;

            //Convert parameters(timeEarliestFromDepart...) passed from sliders to Time Type
            var timeEarliestFromDepartConverted = GetTime(timeEarliestFromDepart);
            var timeLatiestFromDepartConverted  = GetTime(timeLatiestFromDepart);
            var timeEarliestFromArriveConverted = GetTime(timeEarliestFromArrive);
            var timeLatiestFromArriveConverted  = GetTime(timeLatiestFromArrive);
            var timeEarliestToDepartConverted   = GetTime(timeEarliestToDepart);
            var timeLatiestToDepartConverted    = GetTime(timeLatiestToDepart);
            var timeEarliestToArriveConverted   = GetTime(timeEarliestToArrive);
            var timeLatiestToArriveConverted    = GetTime(timeLatiestToArrive);

            //Get the total amount of candidate trips(tripTagTempData) from session
            var tripTagTempData = HttpContext.Session.GetInt32(SessionKeyTripTagTempDataOnewayTrip);

            //store the candidate trips matched the time data from the slider
            var ViewModel       = new List <CandidateTripVM>(); //存储出发航班
            var ViewModelReturn = new List <CandidateTripVM>(); //存储返程航班

            bool timeEarliest;
            bool timeLatiest;
            bool stops;

            for (var tt = 0; tt <= HttpContext.Session.GetInt32(SessionKeyTripTagTempDataOnewayTrip); tt++)
            {
                //Get all the candidate trips from TempData without deleting them(Peek)
                var tempCTVMSerialized = (string)TempData.Peek(tt.ToString());
                var tempCTVM           = JsonConvert.DeserializeObject <CandidateTripVM>(tempCTVMSerialized);

                //match the processed time data of time slider against those in the candidate trips in the Tempdata
                //将表单提交过来的时间数据(timeEarliestFromDepartConverted...)与日期合并后方便与TempData中的时间数据(tempCTVM.DepartTime)进行大小对比
                timeEarliest = tempCTVM.DepartTime >= DateTime.Parse(tempCTVM.DepartTime.Date.ToString("d") + " " + timeEarliestFromDepartConverted) && tempCTVM.ArrivetTime >= DateTime.Parse(tempCTVM.ArrivetTime.Date.ToString("d") + " " + timeEarliestFromArriveConverted);
                timeLatiest  = tempCTVM.DepartTime <= DateTime.Parse(tempCTVM.DepartTime.Date.ToString("d") + " " + timeLatiestFromDepartConverted) && tempCTVM.ArrivetTime <= DateTime.Parse(tempCTVM.ArrivetTime.Date.ToString("d") + " " + timeLatiestFromArriveConverted);
                stops        = tempCTVM.stopList.Count() - 2 == stops0 || tempCTVM.stopList.Count() - 2 == stops1 || tempCTVM.stopList.Count() - 2 == stops2;

                //pick up the candidate trips that meet the 3 conditions down below
                //只对满足以上3组条件的数据进行输出(放入ViewModel/ViewModelReturn中)
                if (timeEarliest && timeLatiest && stops)
                {
                    ViewModel.Add(tempCTVM);
                }
            }
            //pass the matched candidate trips(depart) to the view
            //viewbag存储的只是地址,所以要分成Trips和TripsReturn,同时此处不要用clear函数来清除ViewModel,不然前者会被后者TripsReturn覆盖掉
            ViewBag.Trips = ViewModel;


            for (var tt = HttpContext.Session.GetInt32(SessionKeyTripTagTempDataOnewayTrip) + 1; tt <= HttpContext.Session.GetInt32(SessionKeyTripTagTempDataRoundTrip); tt++)
            {
                //Get all the candidate trips from TempData without deleting them(Peek)
                var tempCTVMSerialized = (string)TempData.Peek(tt.ToString());
                var tempCTVM           = JsonConvert.DeserializeObject <CandidateTripVM>(tempCTVMSerialized);

                timeEarliest = tempCTVM.DepartTime >= DateTime.Parse(tempCTVM.DepartTime.Date.ToString("d") + " " + timeEarliestToDepartConverted) && tempCTVM.ArrivetTime >= DateTime.Parse(tempCTVM.ArrivetTime.Date.ToString("d") + " " + timeEarliestToArriveConverted);
                timeLatiest  = tempCTVM.DepartTime <= DateTime.Parse(tempCTVM.DepartTime.Date.ToString("d") + " " + timeLatiestToDepartConverted) && tempCTVM.ArrivetTime <= DateTime.Parse(tempCTVM.ArrivetTime.Date.ToString("d") + " " + timeLatiestToArriveConverted);
                stops        = tempCTVM.stopList.Count() - 2 == stops0 || tempCTVM.stopList.Count() - 2 == stops1 || tempCTVM.stopList.Count() - 2 == stops2;

                if (timeEarliest && timeLatiest && stops)
                {
                    ViewModelReturn.Add(tempCTVM);
                }
            }

            //pass the matched candidate trips(return) to the view
            ViewBag.TripsReturn = ViewModelReturn;

            //存储slider filter标题(Take off:/Landing:)
            ViewBag.FromCityName = _cookieControl.Get("FromCityName");
            ViewBag.ToCityName   = _cookieControl.Get("ToCityName");

            //return View("Search");
            userAgent = Request.Headers["User-Agent"];
            UserAgent.UserAgent ua = new UserAgent.UserAgent(userAgent);
            ViewBag.userAgent = ua.Browser.IsMobileDevice.ToString();
            if ((b.IsMatch(userAgent) || v.IsMatch(userAgent.Substring(0, 4))))
            {
                return(View("SearchMobile"));
            }
            else
            {
                return(View("Search"));
            }
        }
Example #16
0
        public async Task <IActionResult> Search(string userAgent, string FromCityName, string ToCityName, int FromCityID, int ToCityID, string startTime, string returnTime, int adults, int youths, int children, string cabin, string onewayOrReturn)
        {
            //prevent errors after swaping languages
            //防止在这一步时切换语言文化后出现报错(表单的值为空)
            if (FromCityName != null)
            {
                //store the values submited from form into cookies
                //把页面表单提交传过来的值放入cookie长期保存
                _cookieControl.Set("FromCityName", FromCityName, 1000);
                _cookieControl.Set("ToCityName", ToCityName, 1000);
                _cookieControl.Set("FromCityID", FromCityID.ToString(), 1000);
                _cookieControl.Set("ToCityID", ToCityID.ToString(), 1000);
                _cookieControl.Set("adults", adults.ToString(), 1000);
                _cookieControl.Set("youths", youths.ToString(), 1000);
                _cookieControl.Set("children", children.ToString(), 1000);
                _cookieControl.Set("cabin", cabin, 1000);
                _cookieControl.Set("startTime", startTime, 1000);
                if (returnTime != null)
                {
                    _cookieControl.Set("returnTime", returnTime, 1000);
                }
            }
            else
            {
                //if the parameters of this function is null(meaning the languange was changed in the corresponding view), then fetch parameter values from cookie
                FromCityName   = _cookieControl.Get("FromCityName");
                ToCityName     = _cookieControl.Get("ToCityName");
                FromCityID     = Int32.Parse(_cookieControl.Get("FromCityID"));
                ToCityID       = Int32.Parse(_cookieControl.Get("ToCityID"));
                adults         = Int32.Parse(_cookieControl.Get("adults"));
                youths         = Int32.Parse(_cookieControl.Get("youths"));
                children       = Int32.Parse(_cookieControl.Get("children"));
                cabin          = _cookieControl.Get("cabin");
                onewayOrReturn = "return";
                startTime      = _cookieControl.Get("startTime");
                returnTime     = _cookieControl.Get("returnTime");
            }

            //clear the session values of last request
            //清除上一次的请求时遗留下的session,防止数据错乱
            HttpContext.Session.Clear();

            var departViewModel = new List <CandidateTripVM>();  //传给view的
            var returnViewModel = new List <CandidateTripVM>();  //传给view的

            if (string.IsNullOrEmpty(HttpContext.Session.GetString(SessionKeyAdults)))
            {
                HttpContext.Session.SetInt32(SessionKeyAdults, adults);
                HttpContext.Session.SetInt32(SessionKeyYouths, youths);
                HttpContext.Session.SetInt32(SessionKeyChildren, children);
                HttpContext.Session.SetString(SessionKeyCabin, cabin);
                HttpContext.Session.SetString(SessionKeyonewayOrReturn, onewayOrReturn);
            }

            ViewBag.cabin = cabin;
            //pass on the indicator for "oneway" or "return"
            //传递oneway或者return的信号
            ViewBag.onewayOrReturn = onewayOrReturn;

            ViewBag.stops0 = 0;
            ViewBag.stops1 = 1;
            ViewBag.stops2 = 2;

            //slider的初始值(initial value of slider)
            ViewBag.timeEarliestFromDepart = 0;
            ViewBag.timeLatiestFromDepart  = 1439;
            ViewBag.timeEarliestFromArrive = 0;
            ViewBag.timeLatiestFromArrive  = 1439;
            ViewBag.timeEarliestToDepart   = 0;
            ViewBag.timeLatiestToDepart    = 1439;
            ViewBag.timeEarliestToArrive   = 0;
            ViewBag.timeLatiestToArrive    = 1439;

            //_ScheduleSearching = new ScheduleSearching(_context);
            var departCandidateTrip = new List <CandidateTrip>();

            departCandidateTrip = await _ScheduleSearching.SearchAsync(FromCityID, ToCityID, startTime, adults, youths, children, cabin);

            PopulateViewModel(departViewModel, departCandidateTrip);

            if (onewayOrReturn == "return")
            {
                var returnCandidateTrip = new List <CandidateTrip>();
                returnCandidateTrip = await _ScheduleSearching.SearchAsync(ToCityID, FromCityID, returnTime, adults, youths, children, cabin);

                PopulateViewModel(returnViewModel, returnCandidateTrip);
            }

            //put the entire list of viewmodel into viewbag
            //整个List<CandidateTripVM>的ViewModel放入ViewBag中
            ViewBag.Trips       = departViewModel;
            ViewBag.TripsReturn = returnViewModel;
            //return RedirectToAction(nameof(Index));

            //存储slider filter标题(Take off:/Landing:)
            ViewBag.FromCityName = _cookieControl.Get("FromCityName");
            ViewBag.ToCityName   = _cookieControl.Get("ToCityName");

            userAgent = Request.Headers["User-Agent"];
            UserAgent.UserAgent ua = new UserAgent.UserAgent(userAgent);
            ViewBag.userAgent = ua.Browser.IsMobileDevice.ToString();
            if ((b.IsMatch(userAgent) || v.IsMatch(userAgent.Substring(0, 4))))
            {
                return(View("SearchMobile"));
            }
            else
            {
                return(View());
            }
        }