Beispiel #1
0
        /// <summary>
        /// Generates an action url
        /// </summary>
        /// <param name="actionContext">Action context</param>
        /// <returns>Url</returns>
        public string Action(UrlActionContext actionContext)
        {
            string url = string.Format("https://localhost:5001/{0}/{1}", actionContext.Controller, actionContext.Action);

            string parameters = string.Empty;

            if (actionContext.Values != null)
            {
                foreach (PropertyInfo prop in actionContext.Values.GetType().GetProperties())
                {
                    string value = prop.GetValue(actionContext.Values, null).ToString();

                    if (string.IsNullOrEmpty(parameters))
                    {
                        parameters += "?";
                    }
                    else
                    {
                        parameters += "&";
                    }
                    parameters += string.Format("{0}={1}", prop.Name, HttpUtility.UrlEncode(value));
                }
            }

            return(url + parameters);
        }
        public void And_A_Valid_Report_Does_Not_Exist_Then_Redirect_Home()
        {
            // arrange
            var url = "home/index";
            UrlActionContext actualContext = null;

            var report =
                new ReportBuilder()
                .WithInvalidSections()
                .WithEmployerId("ABCDE")
                .ForCurrentPeriod()
                .WhereReportIsNotAlreadySubmitted()
                .Build();

            _mockUrlHelper.Setup(h => h.Action(It.IsAny <UrlActionContext>())).Returns(url).Callback <UrlActionContext>(c => actualContext = c).Verifiable("Url.Action was never called");
            _reportService.Setup(s => s.GetReport(It.IsAny <string>(), It.IsAny <string>())).Returns(report);
            _reportService.Setup(s => s.CanBeEdited(report)).Returns(false).Verifiable();

            // act
            var result = _controller.Index("YourEmployees");

            // assert
            _mockUrlHelper.VerifyAll();

            var redirectResult = result as RedirectResult;

            Assert.IsNotNull(redirectResult);
            Assert.AreEqual(url, redirectResult.Url);
            Assert.AreEqual("Index", actualContext.Action);
            Assert.AreEqual("Home", actualContext.Controller);
        }
        public override string Action(UrlActionContext actionContext)
        {
            var controller = actionContext.Controller;
            var action     = actionContext.Action;

            return($"You wrote {controller} > {action}!");
        }
Beispiel #4
0
        public void When_The_Report_Is_Submitted_Redirect_To_Home()
        {
            // arrange
            var url = "home/Index";
            UrlActionContext actualContext = null;

            _mockUrlHelper.Setup(h => h.Action(It.IsAny <UrlActionContext>())).Returns(url).Callback <UrlActionContext>(c => actualContext = c).Verifiable("Url.Action was never called");


            var report =
                new ReportBuilder()
                .WithValidSections()
                .WithEmployerId("ABCDEF")
                .ForCurrentPeriod()
                .WhereReportIsAlreadySubmitted()
                .Build();

            _mockReportService.Setup(s => s.GetReport(It.IsAny <string>(), It.IsAny <string>())).Returns(report).Verifiable();
            _mockReportService.Setup(s => s.CanBeEdited(report)).Returns(false).Verifiable();
            _controller.ObjectValidator = GetObjectValidator().Object;

            // act
            var result = _controller.Confirm();

            // assert
            Assert.AreEqual(typeof(RedirectResult), result.GetType());
            var redirectResult = result as RedirectResult;

            Assert.IsNotNull(redirectResult);
            Assert.AreEqual(url, redirectResult.Url);
            Assert.AreEqual(actualContext.Action, "Index");
            Assert.AreEqual(actualContext.Controller, actualContext.Controller);
        }
Beispiel #5
0
        public void And_Report_Is_Not_Editable_Then_Redirect_Home()
        {
            // arrange
            var url = "home/index";
            UrlActionContext actualContext = null;
            var report = new Report();

            _mockUrlHelper.Setup(h => h.Action(It.IsAny <UrlActionContext>())).Returns(url).Callback <UrlActionContext>(c => actualContext = c).Verifiable("Url.Action was never called");

            _reportService.Setup(s => s.GetReport("111", It.IsAny <string>())).Returns(report).Verifiable();
            _reportService.Setup(s => s.CanBeEdited(report)).Returns(false).Verifiable();

            // act
            var result = _controller.Submit(new SectionModel {
                ReportingPeriod = "111"
            });

            // assert
            _mockUrlHelper.VerifyAll();
            _reportService.VerifyAll();

            var redirectResult = result as RedirectResult;

            Assert.IsNotNull(redirectResult);
            Assert.AreEqual(url, redirectResult.Url);
            Assert.AreEqual("Index", actualContext.Action);
            Assert.AreEqual("Home", actualContext.Controller);
        }
Beispiel #6
0
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            var urlHelper = _urlHelperFactory.GetUrlHelper(ViewContext);
            var result    = new TagBuilder("div");

            for (int i = 1; i <= PageModel.TotalPages; i++)
            {
                var tag = new TagBuilder("a");
                PageUrlValues["page"] = i;
                var urlContext = new UrlActionContext
                {
                    Action = PageAction, Values = PageUrlValues
                };
                tag.Attributes["href"] = urlHelper.Action(urlContext);
                if (PageClassesEnabled)
                {
                    tag.AddCssClass(PageClass);
                    tag.AddCssClass(i == PageModel.CurrentPage ? PageClassSelected : PageClassNormal);
                }

                tag.InnerHtml.Append(i.ToString());
                result.InnerHtml.AppendHtml(tag);
            }

            output.Content.AppendHtml(result.InnerHtml);
        }
        public async Task <IActionResult> SendResetPassword(string UserName)
        {
            var user = await _userService.GetUserByEmail(UserName);

            var urlAction = new UrlActionContext {
                Action = "ResetPassword", Controller = "Account", Values = new { email = UserName, code = await _userService.GetResetPasswordCode(user) }, Protocol = Request.Scheme, Host = Request.Host.ToString()
            };

            var resetPasswordEmailModel = new ResetPasswordEmailModel {
                DisplayName = $"{user.FirstName} {user.LastName}", ActionUrl = Url.Action(urlAction)
            };

            var emailRenderService = HttpContext.RequestServices.GetService <IEmailTemplateRenderService>();
            var emailService       = HttpContext.RequestServices.GetService <IEmailService>();

            var message = await emailRenderService.RenderTemplate("EmailTemplates/ResetPasswordEmail", resetPasswordEmailModel, Request.Host.ToString());

            try
            {
                emailService.SendEmail(UserName, "Tic-Tac-Toe Reset Password", message).Wait();
            }
            catch { }

            return(View("ConfirmResetPasswordRequest", resetPasswordEmailModel));
        }
Beispiel #8
0
        private string FindRoute(UrlActionContext urlActionContext)
        {
            if (!_urlRoutesOptions.Any())
            {
                return(null);
            }

            var keys = new List <string>();

            var area = urlActionContext?.Values?.GetProperty <string>("Area");

            if (string.IsNullOrWhiteSpace(area) && _originalUrlHelper.ActionContext.RouteData.Values.ContainsKey("area"))
            {
                area = _originalUrlHelper.ActionContext.RouteData.Values["area"].ToString();
            }
            if (!string.IsNullOrWhiteSpace(area))
            {
                keys.Add(area);
            }

            var controller = urlActionContext.Controller;

            if (string.IsNullOrWhiteSpace(controller) && _originalUrlHelper.ActionContext.RouteData.Values.ContainsKey("controller"))
            {
                controller = _originalUrlHelper.ActionContext.RouteData.Values["controller"].ToString();
            }
            if (!string.IsNullOrWhiteSpace(controller))
            {
                keys.Add(controller);
            }

            if (!string.IsNullOrWhiteSpace(urlActionContext.Action))
            {
                keys.Add(urlActionContext.Action);
            }

            while (keys.Any())
            {
                var key = keys.ToDelimitedString(":");
                if (_urlRoutesOptions.ContainsKey(key))
                {
                    var value = _urlRoutesOptions[key];
                    if (!string.IsNullOrWhiteSpace(value))
                    {
                        if (value.StartsWith("~"))
                        {
                            value = _originalUrlHelper.ActionContext.HttpContext.ResolveUrl(value);
                        }
                        if (urlActionContext.Values != null && value.Contains('{') && value.Contains('}'))
                        {
                            value = urlActionContext.Values.Resolve(value);
                        }
                        return(value);
                    }
                }
                keys.RemoveAt(0);
            }

            return(null);
        }
        public string Action(UrlActionContext actionContext)
        {
            var query     = new StringBuilder();
            var routePath = !string.IsNullOrEmpty(_routeTemplate) ? $"/{_routeTemplate}" : string.Empty;

            var properties = actionContext.Values != null?actionContext.Values.GetType().GetProperties() : new PropertyInfo[0];

            for (var i = 0; i < properties.Length; i++)
            {
                var property      = properties[i];
                var propertyValue = property.GetValue(actionContext.Values);

                routePath = routePath.Replace($"{{{property.Name}}}", propertyValue?.ToString(), StringComparison.InvariantCultureIgnoreCase);

                if (propertyValue == null || !_queryParameterNames.Any(x => x.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase)))
                {
                    continue;
                }

                query.Append(query.Length > 0 ? "&" : "?");
                query.Append(property.Name);
                query.Append("=");
                query.Append(propertyValue);
            }

            return($"{BaseUrl}{routePath}{query}");
        }
Beispiel #10
0
        public async Task <IActionResult> EmailConfirmation(string email)
        {
            _logger.LogInformation($"##Start## Email confirmation process for {email}");

            var user = await _userService.GetUserByEmail(email);

            var urlAction = new UrlActionContext {
                Action     = "ConfirmEmail",
                Controller = "UserRegistration",
                Values     = new { email, code = await _userService.GetEmailConfirmationCode(user) },
                Protocol   = Request.Scheme,
                Host       = Request.Host.ToString()
            };

            var userRegistrationEmail = new UserRegistrationEmailModel {
                DisplayName = $"{user.FirstName} {user.LastName}", Email = email, ActionUrl = Url.Action(urlAction)
            };

            var emailRenderService = HttpContext.RequestServices.GetService <IEmailTemplateRenderService>();

            var message = await emailRenderService.RenderTemplate("EmailTemplates/UserRegistrationEmail", userRegistrationEmail, Request.Host.ToString());

            try
            {
                _emailService.SendEmail(email, "Tic-Tac-Toe Email Confirmation", message).Wait();
            }
            catch (Exception) {
            }

            ViewBag.Email = email;

            return(View());
        }
        private string GenerateRedeemUrl(
            string emailAddress,
            string nonce,
            long notBefore,
            long expires,
            string signature)
        {
            var actionContext = new UrlActionContext
            {
                Protocol   = "https",
                Host       = _options.ActivationHost,
                Controller = _options.ActivationController,
                Action     = _options.ActivationAction,
                Values     = new
                {
                    email = emailAddress,
                    nonce = nonce,
                    nbf   = notBefore,
                    exp   = expires,
                    sig   = signature
                }
            };

            return(Url.Action(actionContext));
        }
Beispiel #12
0
        public async Task <IActionResult> EmailConfirmation(string email)
        {
            _logger.LogInformation($"##Start## Email confirmation process for {email}");
            var user = await _userService.GetUserByEmail(email);

            var urlAction = new UrlActionContext
            {
                Action     = "ConfirmEmail",
                Controller = "UserRegistration",
                Values     = new { email },
                Protocol   = Request.Scheme,
                Host       = Request.Host.ToString()
            };

            var message = $"Thank you for your registration on our web site, please click here to confirm your email " +
                          $"{Url.Action(urlAction)}";

            try
            {
                _emailService.SendEmail(email, "Tic-Tac-Toe Email Confirmation", message).Wait();
            }
            catch (Exception e)
            {
            }

            if (user?.IsEmailConfirmed == true)
            {
                return(RedirectToAction("Index", "GameInvitation", new { email = email }));
            }

            ViewBag.Email = email;

            return(View());
        }
        public override string Action(UrlActionContext actionContext)
        {
            var url    = _urlHelper.Action(actionContext);
            var newUrl = _urlLocalizer.LocalizeLink(url);

            return(newUrl);
        }
Beispiel #14
0
        public static string ListActionUrl(this IHtmlHelper htmlHelper, string actionName, int page, int index = 0)
        {
            var urlHelperFactory = htmlHelper.ViewContext.HttpContext.RequestServices.GetRequiredService <IUrlHelperFactory>();
            var urlHelper        = urlHelperFactory.GetUrlHelper(htmlHelper.ViewContext);

            var pageValue = htmlHelper.GetPageValue();

            pageValue = ReplaceItem(pageValue, page.ToString(), index);

            var actionContext = new UrlActionContext()
            {
                Action = actionName,
                Values = new
                {
                    descending = htmlHelper.GetDescendingValue(),
                    filter     = htmlHelper.GetFilterValue(),
                    page       = pageValue,
                    sort       = htmlHelper.GetSortValue()
                }
            };

            var url = urlHelper.Action(actionContext);

            return(url);
        }
            public string Action(UrlActionContext actionContext)
            {
                var values = (Microsoft.AspNetCore.Routing.RouteValueDictionary)actionContext.Values;

                // throw new NotImplementedException();
                return($"/{values.Values.ElementAt(0)}/");
            }
        private async Task SendEmailTwoFactor(string userName)
        {
            var user = await _userService.GetUserByEmail(userName);

            var urlAction = new UrlActionContext {
                Action = "ValidateTwoFactor", Controller = "Account", Values = new { email = userName, code = await _userService.GetTwoFactorCode(user.UserName, "Email") }, Protocol = Request.Scheme, Host = Request.Host.ToString()
            };

            var twoFactorEmailModel = new TwoFactorEmailModel {
                DisplayName = $"{user.FirstName} {user.LastName}", Email = userName, ActionUrl = Url.Action(urlAction)
            };

            var emailRenderService = HttpContext.RequestServices.GetRequiredService <IEmailTemplateRenderService>();
            var emailService       = HttpContext.RequestServices.GetRequiredService <IEmailService>();

            var message = await emailRenderService.RenderTemplate("EmailTemplates/TwoFactorEmail", twoFactorEmailModel, Request.Host.ToString());

            try
            {
                emailService.SendEmail(userName, "Tic-Tac-Toe Two Factor Code", message).Wait();
            }
            catch
            {
            }
        }
    public override string Action(UrlActionContext urlActionContext)
    {
        if (urlActionContext == null)
        {
            throw new ArgumentNullException(nameof(urlActionContext));
        }

        var values = GetValuesDictionary(urlActionContext.Values);

        if (urlActionContext.Action != null)
        {
            values["action"] = urlActionContext.Action;
        }
        else if (!values.ContainsKey("action") && AmbientValues.TryGetValue("action", out var action))
        {
            values["action"] = action;
        }

        if (urlActionContext.Controller != null)
        {
            values["controller"] = urlActionContext.Controller;
        }
        else if (!values.ContainsKey("controller") && AmbientValues.TryGetValue("controller", out var controller))
        {
            values["controller"] = controller;
        }

        var path = _linkGenerator.GetPathByRouteValues(
            ActionContext.HttpContext,
            routeName: null,
            values,
            fragment: new FragmentString(urlActionContext.Fragment == null ? null : "#" + urlActionContext.Fragment));

        return(GenerateUrl(urlActionContext.Protocol, urlActionContext.Host, path));
    }
        public static IItemWriter <T> Href <T>(this IItemWriter <T> target, UrlActionContext actionContext)
            where T : Element, ILink
        {
            var href = ((BootstrapHelper)target.Helper).CreateUrl(actionContext);

            target.Href(href);
            return(target);
        }
Beispiel #19
0
 public string Action(UrlActionContext actionContext)
 {
     ActionName     = actionContext.Action;
     ControllerName = actionContext.Controller;
     ProtocolScheme = actionContext.Protocol;
     Values         = actionContext.Values.ToString();
     return(ActionName);
 }
Beispiel #20
0
        public override string Action(UrlActionContext actionContext)
        {
            var nonRoundTripUsingQueryStringValues = new Dictionary <string, object>(StringComparer.InvariantCultureIgnoreCase);

            var values = GetValuesDictionary(actionContext.Values);

            foreach (var routeDataStringKey in _options.AmbientRouteDataKeys)
            {
                if (!values.ContainsKey(routeDataStringKey.RouteDataKey) &&
                    AmbientValues.TryGetValue(routeDataStringKey.RouteDataKey, out var value))
                {
                    if (!routeDataStringKey.RoundTripUsingQueryString)
                    {
                        nonRoundTripUsingQueryStringValues.Add(routeDataStringKey.RouteDataKey, value);
                    }

                    values[routeDataStringKey.RouteDataKey] = value;
                }
                else if (!values.ContainsKey(routeDataStringKey.RouteDataKey) && _urlHelper.ActionContext.HttpContext.Request.Query.TryGetValue(routeDataStringKey.RouteDataKey, out var queryStringValues))
                {
                    if (!routeDataStringKey.RoundTripUsingQueryString)
                    {
                        nonRoundTripUsingQueryStringValues.Add(routeDataStringKey.RouteDataKey, queryStringValues.First());
                    }

                    values[routeDataStringKey.RouteDataKey] = queryStringValues.First();
                }
            }

            actionContext.Values = values;

            var url = _urlHelper.Action(actionContext);

            if (url != null)
            {
                var uri = new Uri(url, UriKind.RelativeOrAbsolute);
                if (!uri.IsAbsoluteUri)
                {
                    uri = new Uri($"http://www.domain.com{url}");
                }

                var queryDictionary = QueryHelpers.ParseQuery(uri.Query);

                if (queryDictionary.Keys.Any(k => nonRoundTripUsingQueryStringValues.ContainsKey(k)))
                {
                    foreach (var key in queryDictionary.Keys.Where(k => nonRoundTripUsingQueryStringValues.ContainsKey(k)))
                    {
                        values.Remove(key);
                    }

                    actionContext.Values = values;
                    url = _urlHelper.Action(actionContext);
                }
            }

            return(url);
        }
Beispiel #21
0
        public async Task LogOutAsync()
        {
            var mockAuthenticationManager = new Mock <AuthenticationManager>();
            var mockHttpContext           = new Mock <HttpContext>();

            mockHttpContext.SetupGet(m => m.Authentication)
            .Returns(mockAuthenticationManager.Object);

            var mockRequest = new Mock <HttpRequest>();

            mockRequest.SetupGet(m => m.Scheme)
            .Returns("http");

            mockHttpContext.SetupGet(m => m.Request)
            .Returns(mockRequest.Object);

            mockHttpContext.SetupGet(m => m.User)
            .Returns(new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "user123") })));

            var mockHttpContextAccessor = new Mock <IHttpContextAccessor>();

            mockHttpContextAccessor.SetupGet(m => m.HttpContext)
            .Returns(mockHttpContext.Object);

            var mockTokenAgent = new Mock <ITokenRefreshAgent>();

            mockTokenAgent.Setup(a => a.LogoutTokenAsync("user123", "logoutUrl"))
            .ReturnsAsync("logoutUrl");

            var mockUrlHelperFactory = new Mock <IUrlHelperFactory>();

            UrlActionContext urlActionContext = null;

            var mockUrlHelper = new Mock <IUrlHelper>();

            mockUrlHelper.Setup(m => m.Action(It.IsAny <UrlActionContext>()))
            .Returns <UrlActionContext>(_urlActionContext =>
            {
                urlActionContext = _urlActionContext;
                return("logoutUrl");
            });

            mockUrlHelperFactory.Setup(m => m.GetUrlHelper(It.IsAny <ActionContext>()))
            .Returns(mockUrlHelper.Object);

            var authService = new AuthService(mockHttpContextAccessor.Object, mockTokenAgent.Object, mockUrlHelperFactory.Object);

            var controllerContext = new Mock <ControllerContext>();

            var result = await authService.LogOutAsync(new Microsoft.AspNetCore.Mvc.ControllerContext(), "Home", "Index");

            mockAuthenticationManager.Verify(m => m.SignOutAsync(AuthSchemes.CookieAuth), Times.Once);
            Assert.Equal("logoutUrl", result);
            Assert.Equal("Home", urlActionContext.Controller);
            Assert.Equal("Index", urlActionContext.Action);
            Assert.Equal("http", urlActionContext.Protocol);
        }
                public string Action(UrlActionContext actionContext)
                {
                    if (actionContext.Action == UNRESOLVABLE_ACTION)
                    {
                        return(null);
                    }

                    return($"ActionMock({actionContext.Controller}, {actionContext.Action})");
                }
Beispiel #23
0
        public void The_SectionViewModel_Is_Valid_But_Report_Is_Not_Full_Then_Save_Question_Section()
        {
            // arrange
            Report actualReport = null;
            var    report       =
                new ReportBuilder()
                .WithValidSections()
                .ForCurrentPeriod()
                .WithEmployerId("123")
                .WhereReportIsNotAlreadySubmitted()
                .Build();

            var url = "home/index";
            UrlActionContext actualContext = null;

            _mockUrlHelper.Setup(h => h.Action(It.IsAny <UrlActionContext>())).Returns(url).Callback <UrlActionContext>(c => actualContext = c).Verifiable("Url.Action was never called");

            _reportService.Setup(s => s.GetReport("222", It.IsAny <string>())).Returns(report).Verifiable();
            _reportService.Setup(s => s.SaveReport(It.IsAny <Report>(), It.IsAny <UserModel>())).Callback <Report, UserModel>((r, u) => actualReport = r).Verifiable("Report was not saved");
            _reportService.Setup(s => s.CanBeEdited(report)).Returns(true).Verifiable();
            _mockUserService.Setup(s => s.GetUserModel(It.IsAny <ClaimsPrincipal>())).Returns(new UserModel()).Verifiable();

            var sectionModel = new SectionModel
            {
                Id = "SubSectionOne",
                ReportingPeriod = "222",
                Questions       = new []
                {
                    new QuestionViewModel
                    {
                        Id     = "atEnd",
                        Answer = "123,000"
                    },
                    new QuestionViewModel
                    {
                        Id     = "atStart",
                        Answer = ""
                    }
                }
            };            // act
            var result = _controller.Submit(sectionModel);

            // assert
            _mockUrlHelper.VerifyAll();
            _reportService.VerifyAll();
            _mockUserService.VerifyAll();

            var redirectResult = result as RedirectResult;

            Assert.IsNotNull(redirectResult);
            Assert.AreEqual(url, redirectResult.Url);
            Assert.AreEqual("Edit", actualContext.Action);
            Assert.AreEqual("Report", actualContext.Controller);

            Assert.IsNotNull(actualReport);
            Assert.IsFalse(actualReport.IsValidForSubmission());
        }
        protected override void Given()
        {
            var url = "Home/Index";
            UrlActionContext actualContext = null;

            MockUrlHelper.Setup(h => h.Action(It.IsAny <UrlActionContext>())).Returns(url).Callback <UrlActionContext>(c => actualContext = c).Verifiable("Url.Action was never called");

            _mockReportService.Setup(s => s.GetReport(It.IsAny <string>(), It.IsAny <string>())).Throws(new Exception("get report Error"));
        }
Beispiel #25
0
        public async void TestRegister_Return_OkResult(RegisterRequest registerRequest, string description)
        {
            //Arrange
            var user = new AppUser
            {
                Email         = registerRequest.Email,
                UserName      = registerRequest.UserName,
                RefreshTokens = new List <RefreshToken>(),
                Id            = Guid.NewGuid().ToString()
            };

            fakeUserManager.Setup(x => x.FindByEmailAsync(user.Email))
            .Returns(Task.FromResult(users.FirstOrDefault <AppUser>(u => u.Email == user.Email) == null ? null : user));
            fakeUserManager.Setup(x => x.FindByNameAsync(user.UserName))
            .Returns(Task.FromResult(users.FirstOrDefault <AppUser>(u => u.UserName == user.UserName) == null ? null : user));

            fakeUserManager.Setup(x => x.CreateAsync(It.IsAny <AppUser>(), It.IsAny <string>()))
            .ReturnsAsync(IdentityResult.Success).Callback <AppUser, string>((x, y) => context.Users.Add(new AppUser
            {
                Email = x.Email
            }));

            // create url helper mock
            Type t           = typeof(UserServiceTest);
            var  httpContext = new Mock <HttpContext>().Object;

            actionContextAccessor.Setup(x => x.ActionContext).Returns(new ActionContext(
                                                                          httpContext,
                                                                          new Microsoft.AspNetCore.Routing.RouteData(),
                                                                          new ControllerActionDescriptor()
            {
                MethodInfo = t.GetMethod(nameof(UserServiceTest.TestRegister_Return_OkResult))
            }));


            mockUrlHelper = new Mock <IUrlHelper>();

            mockUrlHelperFactory.Setup(x => x.GetUrlHelper(It.IsAny <ActionContext>())).Returns(mockUrlHelper.Object);
            mockUrlHelper.SetupGet(h => h.ActionContext).Returns(actionContextAccessor.Object.ActionContext);

            UrlActionContext actual = null;

            mockUrlHelper.Setup(h => h.Action(It.IsAny <UrlActionContext>()))
            .Callback((UrlActionContext context) => actual = context);

            fakeUserManager.Setup(x => x.GenerateEmailConfirmationTokenAsync(It.IsAny <AppUser>())).ReturnsAsync("");
            mockEmailSender.Setup(x => x.SendEmailAsync(It.IsAny <Message>())).Returns(() => Task.FromResult(""));



            //Act
            var data = await _userService.Object.Register(registerRequest);


            //Assert
            Assert.IsType <OkObjectResult>(data);
        }
        private string GenerateUrlUsingUrlHelper(IUrlHelper urlHelper, UrlActionContext urlActionContext)
        {
            var url = urlHelper.Action(urlActionContext);

            // Ugly patch in order to use "@" in place of "%40"
            // Ugly patch in order to use ":" in place of "%3A"
            url = url?.Replace("%40", "@").Replace("%3A", ":");

            return(url);
        }
        /// <inheritdoc />
        public virtual string Action(UrlActionContext actionContext)
        {
            if (actionContext == null)
            {
                throw new ArgumentNullException(nameof(actionContext));
            }

            actionContext.Values = AddApiVersionRouteValueIfNecessary(actionContext.Values);
            return(Url.Action(actionContext));
        }
Beispiel #28
0
        public string Action(UrlActionContext urlActionContext)
        {
            var result = _originalUrlHelper.Action(urlActionContext);

            if (!string.IsNullOrWhiteSpace(result))
            {
                return(result);
            }
            return(FindRoute(urlActionContext));
        }
        public async Task <IActionResult> EmailConfirmation(string email)
        {
            var user = await _userService.GetUserByEmail(email);

            var urlAction = new UrlActionContext
            {
                Action     = "ConfirmEmail",
                Controller = "UserRegistration",
                Values     = new {
                    email,
                    code = await _userService.GetEmailConfirmationCode(user)
                },
                Protocol = Request.Scheme,
                Host     = Request.Host.ToString()
            };

            var userRegistrationEmail = new UserRegistrationEmailModel
            {
                DisplayName = $"{user.FirstName} {user.LastName}",
                Email       = email,
                ActionUrl   = Url.Action(urlAction)
            };

            var emailRenderService = HttpContext.RequestServices.GetService <IEmailTemplateRenderService>();
            var message            = await emailRenderService.RenderTemplate("EmailTemplates/UserRegistrationEmail",
                                                                             userRegistrationEmail, Request.Host.ToString());

            try
            {
                _emailService.SendEmail(email, "Potwierdzenie adresu e-mail w grze Kółko i krzyżyk", message).Wait();
            }
            catch (Exception e)
            {
            }

            if (user?.IsEmailConfirmed == true)
            {
                return(RedirectToAction("Index", "GameInvitation",
                                        new { email }));
            }

            ViewBag.Email = email;
            return(View());

            //Symulowanie potwierdzenia adresu email
            //if(user?.IsEmailConfirmed == true)
            //{
            //    return RedirectToAction("Index", "GameInvitation", new
            //    {
            //        email
            //    });
            //}
            //ViewBag.Email = email;
            //return View();
        }
Beispiel #30
0
        private static string Action <TController>(
            this IUrlHelper helper,
            Expression <Func <TController, Task> > action,
            UrlActionContext actionContext)
            where TController : class
        {
            ExpressionRouteValues expressionRouteValues = GetExpresionRouteHelper(helper).Resolve(action, actionContext.Values);

            ApplyRouteValues(actionContext, expressionRouteValues);
            return(helper.Action(actionContext));
        }
Beispiel #31
0
 public override string Action(UrlActionContext actionContext)
 {
     return ConvertToLowercaseUrl(base.Action(actionContext));
 }
Beispiel #32
0
 public string Action(UrlActionContext actionContext) => string.Empty;
Beispiel #33
0
 public string Action(UrlActionContext actionContext)
 {
     throw new NotImplementedException();
 }