private ChallengeViewModel GetChallengerView(int pax, int cargo, long paxWeight, string departure, string arrival, string type, long totalPayment, long distance, string weightUnit, int jobId = 0)
        {
            var departureModel = AirportDatabaseFile.FindAirportInfo(departure);
            var arrivalModel   = AirportDatabaseFile.FindAirportInfo(arrival);

            var model = new ChallengeViewModel()
            {
                WeightUnit    = GetWeightUnit(Request),
                ArrivalICAO   = arrivalModel.ICAO,
                DepartureICAO = departureModel.ICAO,
                Cargo         = cargo,
                Dist          = distance,
                Pax           = pax,
                PaxWeight     = paxWeight,
                Type          = type,
                TotalPayment  = totalPayment,
                JobId         = jobId
            };

            switch (type)
            {
            case "Civilian":
                model.Briefing = $@"The biggest soccer team charter an unscheduled flight to participate in the championship. 
                The flight will depart from {departureModel.City} with {pax} players and all team delegation. 
                For the team's luggage and equipment will be loaded {model.Cargo}{weightUnit} in the hold of the plane.
                The final destination is {arrivalModel.City} airport. 
                The total payment involved is ${model.TotalPayment}.
                The captain will earn ${model.PaymentCaptain} when complete.
                The creator of the challenge will earn ${model.PaymentCreator}.";

                model.WaterMarkImg = "/Content/img/challenger/civilian-water-mark-002.png";
                break;

            case "Military":
                model.Briefing     = $@"The order of crew is transport the Defence Minister and his retinue of peace 
                from {departureModel.City} to {arrivalModel.City} (distance is {model.Dist} NM). 
                For this mission, the aircraft will take {pax} people on board and {model.Cargo}{weightUnit} of cargo 
                (total payload is {model.TotalPayload}{weightUnit}). 
                The total payment involved is ${model.TotalPayment}.
                The captain will earn ${model.PaymentCaptain} when complete this mission.
                The creator of the challenge will earn ${model.PaymentCreator}.";
                model.WaterMarkImg = "/Content/img/challenger/military-water-mark-002.png";
                break;

            case "Rescue":
                model.Briefing = $@"A group of students are lost in a park at {arrivalModel.City}. 
                The only hope for the group is a speedy air rescue. The rescue aircraft will take off from {departureModel.City}
                with {pax} doctors and firefighters aboard, and {model.Cargo}{weightUnit} of rescue and fire containment equipment. 
                The total payment involved is ${model.TotalPayment}.
                The captain will earn ${model.PaymentCaptain} when complete this mission.
                The creator of the challenge will earn ${model.PaymentCreator}.";

                model.WaterMarkImg = "/Content/img/challenger/rescue-water-mark-001.png";
                break;

            default:
                break;
            }
            return(model);
        }
        private ChallengeViewModel CreateChallengeViewModel(Challenge challengeData)
        {
            var currentUser        = SessionManager.GetCurrentUser();
            var challengeViewModel = new ChallengeViewModel()
            {
                Opponents = challengeData.Participants
                            .Where(x => !string.Equals(x.User.Email, currentUser.AthleteEmail, StringComparison.OrdinalIgnoreCase))
                            .Select(p => new UserViewModel(p.User)).ToList(),

                ChallengeStatus = (ChallengeStatus)challengeData.ChallengeStatus,
                ChallengeType   = (ChallengeType)challengeData.ChallengeType,
                StartTime       = challengeData.StartTime,
                EndTime         = challengeData.EndTime,
                Wager           = challengeData.Wager,
            };

            if ((ChallengeType)challengeData.ChallengeType == ChallengeType.SegementTime)
            {
                long segmentId;
                if (long.TryParse(challengeData.ChallengeObjective, out segmentId))
                {
                    challengeViewModel.SegmentData = CreateSegmentViewModel(segmentId);
                }
            }

            return(challengeViewModel);
        }
        // GET: Challenge
        public ActionResult Index()
        {
            var dbContext = new ApplicationDbContext();
            var user      = dbContext.Users.FirstOrDefault(u => u.UserName == User.Identity.Name);

            var model = new ChallengeViewModel()
            {
                Pax        = 100,
                Cargo      = 1000,
                PaxWeight  = 84,
                WeightUnit = GetWeightUnit(Request)
            };

            var challengeList = dbContext.JobDbModels.Where(c =>
                                                            !c.IsDone && c.IsChallenge &&
                                                            c.ChallengeExpirationDate > DateTime.Now &&
                                                            c.User == null)
                                .OrderBy(j => j.Id).ToList();

            ViewBag.ChallengeCount = challengeList.Count();

            challengeList.ForEach(x =>
            {
                x.WeightUnit = GetWeightUnit(Request);
                x.IsChallengeFromCurrentUser = x.ChallengeCreatorUserId == user.Id;
            });

            model.UserActiveChallenges = GetUserActiveChallenges(user, dbContext);
            model.Challenges           = challengeList.ToPagedList(1, 25);
            ViewBag.TitleChallenge     = "Available Challenges";

            return(View(model));
        }
        public IHttpActionResult GetChallenges()
        {
            var challenges = RepositoryProvider.Get <ChallengeRepository>().GetAvailableChallenges(CurrentAccess.UserId);
            var result     = challenges.Select(p => ChallengeViewModel.Create(p, CurrentAccess.UserId)).ToList();

            return(Ok(result));
        }
Exemple #5
0
        public static void UseSingleChallenge(IEventStore eventStore)
        {
            if (ChallengeViewModels.Any())
            {
                return;
            }
            var id          = ChallengeId;
            var description = "Hundre pushups hver dag";
            var createEvent = new ChallengeCreated(id, 100, description, DateTime.Now.AddDays(-5));
            var viewModel   = new ChallengeViewModel
            {
                Id               = id.Guid,
                Desciption       = description,
                DailyRepetitions = 100,
                StartDate        = DateTime.Now.AddDays(-5),
                ActiveMonday     = true,
                ActiveTuesday    = true,
                ActiveWednesday  = true,
                ActiveThursday   = true,
                ActiveFriday     = true,
                ActiveSaturday   = true,
                ActiveSunday     = true,
                Duration         = TimeSpan.FromDays(30),
                TotalRepetitions = 460
            };

            eventStore.Add(id, new List <IEvent> {
                createEvent
            });
            ChallengeViewModels.Add(viewModel);
        }
Exemple #6
0
        public IActionResult Challenge([FromQuery] ChallengeViewModel challengeVm)
        {
            if (string.IsNullOrEmpty(challengeVm.ReturnUrl))
            {
                challengeVm.ReturnUrl = "";
            }

            // validate returnUrl - either it is a valid OIDC URL or back to a local page
            // If the project will redirect back to a mobile app, remove this code
            if (Url.IsLocalUrl(challengeVm.ReturnUrl) == false)
            {
                // user might have clicked on a malicious link - should be logged
                throw new Exception("invalid return URL");
            }

            // start challenge and roundtrip the return URL and scheme
            var props = new AuthenticationProperties
            {
                RedirectUri = Url.Action(nameof(Callback)),
                Items       =
                {
                    { "returnUrl", challengeVm.ReturnUrl },
                    { "scheme",    challengeVm.Scheme    },
                }
            };

            return(Challenge(props, challengeVm.Scheme));
        }
        public ActionResult ShowChallengeDetails(int jobId)
        {
            var dbContext      = new ApplicationDbContext();
            var user           = dbContext.Users.FirstOrDefault(u => u.UserName == User.Identity.Name);
            var userStatistics = GetUserStatistics(user.Id);
            var viewModel      = new ChallengeViewModel();
            var jobDb          = dbContext.JobDbModels.FirstOrDefault(j => j.Id == jobId);

            if (jobDb != null)
            {
                var weightUnit = GetWeightUnit(Request);
                var cargo      = GetWeight(Request, jobDb.Cargo, userStatistics);
                var paxWeight  = jobDb.Pax * GetWeight(Request, jobDb.PaxWeight, userStatistics);
                viewModel = GetChallengerView((int)jobDb.Pax, (int)cargo, paxWeight, jobDb.DepartureICAO, jobDb.ArrivalICAO, jobDb.ChallengeType.ToString(), jobDb.Pay, jobDb.Dist, weightUnit, jobId);
            }
            else
            {
                TempData["ErroMessage"] = @"This challenge not exist.";
            }

            if (!jobDb.IsActivated)
            {
                dbContext.JobDbModels.Where(j => j.User.Id == user.Id && j.IsActivated).ToList().ForEach(x =>
                                                                                                         x.IsActivated = false
                                                                                                         );
                jobDb.IsActivated = true;
                dbContext.SaveChanges();
                TempData["JobsUpdated"] = "When jobs are updated.";
            }

            TempData["ShowDetails"] = "Show Challenge details.";

            return(PartialView("BriefingView", viewModel));
        }
Exemple #8
0
 public SelecteChallengePage(InsterUserModel insterUser)
 {
     InitializeComponent();
     this.insterUSer = insterUser;
     BindingContext  = challangeViewModel = new ChallengeViewModel();
     challangeViewModel.navigation = Navigation;
 }
Exemple #9
0
        private ActionResult ReturnToChallenge(ChallengeViewModel model)
        {
            var uri         = $"views/accounts/challenge/{model.ChallengeId}";
            var redirectUri = new Uri(_siteConnector.Services[SupportServices.Portal], uri);

            return(Redirect(redirectUri.AbsoluteUri));
        }
        public Challenge CreateChallenge(RestContext context, ChallengeViewModel cvm )
        {
            var challenge = CreateInstance();

            FillGeneralData(challenge, cvm);
            FillSpecificData(challenge, context, cvm);

            return challenge;
        }
Exemple #11
0
        public async Task <ActionResult> AccountPayments(int id, int tries = 1)
        {
            Debug.WriteLine($"App-Debug: {(nameof(AccountsController))} {nameof(AccountPayments)} {id} {tries}");
            var entityType = "Account.Payments";

            if (await _siteConnector.Challenge(
                    _identity, $"api/challenge/required/{entityType}/{id}"))
            {
                var model = new ChallengeViewModel
                {
                    MenuType   = _menuType,
                    EntityType = entityType,
                    Identifier = $"{id}",
                    Identity   = _identity,
                    ReturnTo   = $"{_siteConnector.Services[SupportServices.Portal]}views/accounts/{id}/payments",
                    Tries      = tries
                };
                MvcApplication.Challenges.Add(model.ChallengeId, model);
                return(RedirectToAction("Challenge", "Challenge", new { model.ChallengeId }));
            }

            await _siteConnector.Challenge(_identity, $"api/challenge/refresh/{entityType}/{id}");

            var paymentsView =
                await _siteConnector.DownloadView(SupportServices.Portal, _identity, $"resources/payments/accounts/{id}");

            var accountPaymentsViewModel = new AccountPaymentsViewModel
            {
                Account = _accountViewModels.Accounts.FirstOrDefault(x => x.AccountId == id),
                View    = paymentsView
            };

            if (NavItem.IsAResourceRequest(Request))
            {
                return(View("_accountPayments", accountPaymentsViewModel));
            }

            var identifiers = new Dictionary <string, string> {
                { "accountId", $"{id}" }
            };
            var menuNavItems = NavItem.TransformNavItems(
                MvcApplication.NavItems
                .Where(x => x.Key.StartsWith($"{_menuType}"))
                .ToDictionary(x => x.Key, x => x.Value),
                _siteConnector.Services[SupportServices.Portal],
                identifiers
                ).Select(s => s.Value).ToList();

            ViewBag.Menu = Menu.ConfigureMenu(menuNavItems, entityType,
                                              new List <string> {
                $"{entityType}", $"{entityType}.All"
            },
                                              MenuOrientations.Horizontal);

            return(View("_accountPayments", accountPaymentsViewModel));
        }
Exemple #12
0
 private void SetSelectedWeekdays(ChallengeViewModel model)
 {
     sunday.SetState(model.ActiveSunday);
     saturday.SetState(model.ActiveSaturday);
     friday.SetState(model.ActiveFriday);
     thursday.SetState(model.ActiveThursday);
     wednesday.SetState(model.ActiveWednesday);
     tuesday.SetState(model.ActiveTuesday);
     monday.SetState(model.ActiveMonday);
 }
 private void FillGeneralData(Challenge challenge, ChallengeViewModel data)
 {
     challenge.Date = DateTime.Now;
     challenge.Done = false;
     challenge.Type = data.Type;
     if (data.Type.Contains(".")) {
         string[] parts = data.Type.Split('.');
         challenge.Type = parts[0];
         data.Type = parts[1];
     }
 }
Exemple #14
0
        static async Task Main(string[] args)
        {
            var chatIp = "localhost:9100";
            //setup our DI
            var serviceProvider = new ServiceCollection()
                                  .AddHttpClient()
                                  .AddSingleton <IHttpHandler, HttpHandler>()
                                  .AddSingleton <IIdentityService, IdentityService>()
                                  .BuildServiceProvider();

            //configure console logging
            var httpHandler     = serviceProvider.GetService <IHttpHandler>();
            var identityService = serviceProvider.GetService <IIdentityService>();


            Console.WriteLine("Enter your AccessToken!");
            var accessToken = ReadLine().Replace("\r\n", "").Trim();

            var userId = await identityService.GetUserId(accessToken);

            var challengeViewModel = new ChallengeViewModel(accessToken);

            Console.WriteLine("Enter UserId whom you would like to talk with!");
            var chatUserId = ReadLine().Replace("\r\n", "").Trim();

            var createChatModel = await httpHandler.AuthPostAsync <CreateChatModel>(accessToken, "http://" + chatIp, $"/api/Chat/ChatRoom/{chatUserId}");

            await challengeViewModel.ChatConnect();

            await challengeViewModel.ChallengeConnect();

            await challengeViewModel.GameConnect();

            while (true)
            {
                Console.WriteLine("Enter your message!");
                var message = ReadLine();

                await challengeViewModel.SendChatMessage(chatUserId, message, createChatModel.ChatRoomId);
            }

            //await challengeViewModel.ChallengeConnect();
            //await challengeViewModel.GameConnect();
            //Thread.Sleep(500);
            //await challengeViewModel.SendChallenge();
            //challengeViewModel.SendMessage("User XXX", "Message 1");
            //var key = Console.ReadKey();
            //if (key.KeyChar == 1)
            //    Console.WriteLine(1);
        }
        public async Task <IHttpActionResult> GetChallenge(Guid challengeId)
        {
            var challenge =
                await
                RepositoryProvider.Get <ChallengeRepository>().Get(p => p.ChallengeId == challengeId)
                .Include("Deeds")
                .FirstOrDefaultAsync();

            if (challenge == null)
            {
                return(NotFound());
            }

            var result = ChallengeViewModel.Create(challenge, CurrentAccess.UserId);

            return(Ok(result));
        }
Exemple #16
0
        public void SetChallenge(ChallengeViewModel model)
        {
            Model = model;
            ItemView.FindViewById <TextView>(Resource.Id.challenge_days_left).Text         = $"{dayString} {model.DaysLeft}";
            ItemView.FindViewById <TextView>(Resource.Id.challenge_description).Text       = model.Desciption;
            ItemView.FindViewById <TextView>(Resource.Id.challenge_total_repetitions).Text = model.TotalRepetitions.ToString();


            monday    = ItemView.FindViewById <CustomToggleButton>(Resource.Id.monday);
            tuesday   = ItemView.FindViewById <CustomToggleButton>(Resource.Id.tuesday);
            wednesday = ItemView.FindViewById <CustomToggleButton>(Resource.Id.wednesday);
            thursday  = ItemView.FindViewById <CustomToggleButton>(Resource.Id.thursday);
            friday    = ItemView.FindViewById <CustomToggleButton>(Resource.Id.friday);
            saturday  = ItemView.FindViewById <CustomToggleButton>(Resource.Id.saturday);
            sunday    = ItemView.FindViewById <CustomToggleButton>(Resource.Id.sunday);

            SetSelectedWeekdays(model);
            SetMeasurements(model.Measurements);
        }
Exemple #17
0
        public IHttpActionResult InsertChallenge(ChallengeViewModel cvm)
        {
            try
            {
                if (cvm == null || cvm.Type == null)
                {
                    throw new ArgumentException("No data.");
                }
                var challenge = cvm.CreateFactory().CreateChallenge(_context, cvm);
                User.AddChallenge(challenge);

                _context.SaveChanges();
                return(Ok(challenge));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Exemple #18
0
        public async Task <IActionResult> EncryptAndSave(ChallengeViewModel challengeViewModel)
        {
            if (!this.ModelState.IsValid)
            {
                challengeViewModel.Success = false;
                return(View("Views/Challenge/Index.cshtml", challengeViewModel));
            }


            var resp = await _serviceHelper.PostRequest <ChallengeDto, ApiResultDto <string> >(_apiEndpoints.ClientName, _apiEndpoints.Challenge.Post,
                                                                                               new ChallengeDto()
            {
                Input    = challengeViewModel.ProtectedData,
                Username = HttpContext.User.Identity.Name
            });

            challengeViewModel.Success = resp?.Error == null;

            return(View("Views/Challenge/Index.cshtml", challengeViewModel));
        }
Exemple #19
0
        /// <summary>
        ///     Directs to overview page of challenges for a specific user
        /// </summary>
        /// <returns>workout overview page</returns>
        public async Task <IActionResult> Challenges()
        {
            var user = await GetCurrentUserAsync();

            var receivedChallenges = await _challengeService.GetReceivedChallengesAsync(user.Id);

            var givenChallenges = await _challengeService.GetGivenChallengesAsync(user.Id);

            if (receivedChallenges == null || givenChallenges == null)
            {
                return(StatusCode(500));
            }

            var model = new ChallengeViewModel
            {
                ReceivedChallenges = receivedChallenges.AsEnumerable(),
                GivenChallenges    = givenChallenges.AsEnumerable()
            };


            return(View(model));
        }
        public ActionResult Index()
        {
            List <ChallengeDTO> challenges = new List <ChallengeDTO>();

            challenges.Add(new ChallengeDTO()
            {
                Theme = "Cemitérios", AnnouncementDate = DateTime.Now.AddMonths(3)
            });
            challenges.Add(new ChallengeDTO()
            {
                Theme = "Fantasmas", AnnouncementDate = DateTime.Now.AddMonths(6)
            });
            challenges.Add(new ChallengeDTO()
            {
                Theme = "Faroeste", AnnouncementDate = DateTime.Now.AddMonths(-7)
            });

            ChallengeViewModel challengeViewModel = new ChallengeViewModel();

            challengeViewModel.Challenges = challenges;
            return(View(challengeViewModel));
        }
Exemple #21
0
        public async Task <IActionResult> CreateChallenge([FromBody] ChallengeViewModel challengeViewModel)
        {
            try
            {
                var course = await _courseRepository.FindCourse(challengeViewModel.CourseId);

                if (course == null)
                {
                    return(BadRequest("Unable to find course"));
                }

                var challenge = new Challenge
                {
                    CourseId            = challengeViewModel.CourseId,
                    Description         = challengeViewModel.Description,
                    Latitude            = challengeViewModel.Latitude,
                    IsLocationDependant = challengeViewModel.IsLocationDependant,
                    Longitude           = challengeViewModel.Longitude,
                    Name = challengeViewModel.Name,
                    ShortAnswerQuestion    = challengeViewModel.ShortAnswerQuestion,
                    ShortAnswerSolution    = challengeViewModel.ShortAnswerSolution,
                    ChallengeType          = challengeViewModel.ChallengeType,
                    MultipleChoiceSolution = challengeViewModel.MultipleChoiceSolution,
                    MultipleChoiceOptions  = challengeViewModel.MultipleChoiceOptions,
                    MultipleChoiceQuestion = challengeViewModel.MultipleChoiceQuestion,
                    ParagraphText          = challengeViewModel.ParagraphText
                };

                await _challengeRepository.CreateChallenge(challenge);

                return(Ok(challenge));
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.Message);
                return(BadRequest(new ErrorMessage(ex)));
            }
        }
        public async Task <ActionResult> Index(string id, ChallengeEntry challengeEntry)
        {
            var response = await _handler.Handle(Map(challengeEntry));

            if (response.IsValid)
            {
                return(Json(new ChallengeValidationResult
                {
                    IsValidResponse = true
                }));
            }


            var model = new ChallengeViewModel
            {
                Characters = response.Characters,
                Id         = challengeEntry.Id,
                Url        = challengeEntry.Url,
                HasError   = true
            };

            return(View(model));
        }
        public IHttpActionResult InsertChallenge(ChallengeViewModel cvm)
        {
            try
            {

                if (cvm == null || cvm.Type == null)
                {
                    throw new ArgumentException("No data.");
                }
                var challenge = cvm.CreateFactory().CreateChallenge(_context, cvm);
                User.AddChallenge(challenge);

                _context.SaveChanges();
                return Ok(challenge);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        protected override void FillSpecificData(Challenge challenge, RestContext context, ChallengeViewModel data)
        {
            var c = challenge as CreativeCookingChallenge;

            if (data.IngredientsId == null)
                throw new NullReferenceException("Ingredients are required.");

            if (data.RecipeId == -1)
                throw new ArgumentException("Well then please just give a recipe.");

            var recipe = context.Recipes.FirstOrDefault(r => r.RecipeId == data.RecipeId);
            if (recipe == null)
                throw new NullReferenceException($"No recipe was found with id {data.RecipeId}.");
            c.Recipe = recipe;

            foreach (int ingredientId in data.IngredientsId) {
                var ingredient = context.Ingredients.FirstOrDefault(i => i.IngredientId == ingredientId);
                if (ingredient != null)
                    c.Ingredients.Add(ingredient);
            }
            c.Thumbnail = recipe.Image;
            c.Earnings = (int)(1.5 * c.Ingredients.Count);
        }
        protected override void FillSpecificData(Challenge challenge, RestContext context, ChallengeViewModel data)
        {
            var recipe = context.Recipes.FirstOrDefault(r => r.RecipeId == data.RecipeId);
            var c = (challenge as RecipeChallenge);
            if (recipe == null)
                throw new NullReferenceException($"Recipe with id {data.RecipeId} was not found.");

            c.Recipe = recipe;
            c.PrepareFor = (TargetSubject)R.Next(0, 4);
            c.Earnings = 1;
            c.Thumbnail = recipe.Image;
        }
        protected override void FillSpecificData(Challenge challenge, RestContext context, ChallengeViewModel data)
        {
            var restaurant = context.Restaurants.FirstOrDefault(r => r.RestaurantId == data.RestaurantId);
            var c = (challenge as RestaurantChallenge);
            if (restaurant == null)
                throw new NullReferenceException($"Restaurant with id {data.RestaurantId} was not found.");

            c.Earnings = 3;
            c.Restaurant = restaurant;
        }
 protected override void FillSpecificData(Challenge challenge, RestContext context, ChallengeViewModel data)
 {
 }
 /// <summary>
 /// Fill the challenge with challengespecific data.
 /// </summary>
 /// <param name="challenge">The object to be filled.</param>
 /// <param name="context">Context where you can get data.</param>
 protected abstract void FillSpecificData(Challenge challenge, RestContext context, ChallengeViewModel data);