Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Adriano Fabri 459 posts 1602 karma points
    Apr 07, 2021 @ 07:56
    Adriano Fabri
    0

    Umbraco 8 - How to call custom external methods from view

    Hi to all,

    I'm trying to call some external methods that return a bool value

    I already write the methods but a I can't call them from the view in umbraco 8.

    These methods must be called before each page is displayed and check different things (ex. authentication, cutom membership group, etc.)

    Can anyone help me?

    Thank you

    A.

  • Alex Skrypnyk 6132 posts 23951 karma points MVP 7x admin c-trib
    Apr 07, 2021 @ 14:00
    Alex Skrypnyk
    0

    Hi Adriano

    Did you add a reference to an external library in the Umbraco project? Typically, stuff like you described should be called in Umbraco render controllers, authentication even in the filter, or before Umbraco page execution.

    Can you maybe provide code examples?

    Thanks,

    Alex

  • Adriano Fabri 459 posts 1602 karma points
    Apr 13, 2021 @ 15:12
    Adriano Fabri
    0

    Hi Alex, tank you for the answer and sorry for my delay.

    The problem is that when I open a page I must do some checks (ex. on login state, members, and other things).

    So...I tried to create a custom surface controller but when I try to call it with @Html.Action("ChecksBeforeRenderPage","AFController"), but I receive some errors

    I tried to create my custom render mvc controller but I cannot call my custom method.

    What I wrong?

    Can you give me a simple example how can I do that?

    Thank you A.

  • Alex Skrypnyk 6132 posts 23951 karma points MVP 7x admin c-trib
    Apr 13, 2021 @ 18:58
    Alex Skrypnyk
    0

    Did you add a reference to your external library on your Umbraco installation? Why you are not able to call your custom method? what is the error?

    Thanks,

    Alex

  • Adriano Fabri 459 posts 1602 karma points
    Apr 14, 2021 @ 08:18
    Adriano Fabri
    0

    Yeah, I referenced the library in the view

    This is my code:

    View

    @inherits Umbraco.Web.Mvc.UmbracoViewPage
    @using AF.Tools.For.UmbracoV8.Controllers
    @using Umbraco.Web
    @{
        Layout = null;
    
        //Check SSO Auth status
        @Html.Action("CheckSSOAuth","ADFS");
    }
    
    //When SSO authentication pass, the page can be displayed
    

    Controller

    using Umbraco.Web;
    using Umbraco.Web.Composing;
    using Umbraco.Web.Models;
    using Umbraco.Web.Mvc;
    
    namespace AF.Tools.For.UmbracoV8.Controllers
    {
        public class ADFSController : SurfaceController
        {
            protected static NameValueCollection ldapSettings = (NameValueCollection)ConfigurationManager.GetSection("ldapSettings");
            protected static string LDAPConnectionString = ldapSettings["ADLDAPConnectionString"].ToString();
            protected static string ADDomain = ldapSettings["ADDomain"].ToString();
            protected static string ADPath = ldapSettings["ADPath"].ToString();
            protected static string ADAdmUsername = ldapSettings["ADDomain"].ToString() + "\\" + ldapSettings["ADAdmUsername"].ToString();
            protected static string ADAdmPassword = ldapSettings["ADAdmPassword"].ToString();
            protected static UserPrincipal ADUser = null;
    
            public ActionResult CheckSSOAuth()
            {
            string ReturnUrl = Request.Url.AbsoluteUri;
            string redirectUrl = "https://xxxxxxxxxxxxxxx/login/?returl=" + ReturnUrl;
            var SamlResponseCookie = Request.Cookies["samlresponse"];
            var UserInfoCookie = Request.Cookies["userinfo"];
    
            LoginStatusModel UserStatus = Members.GetCurrentLoginStatus();
    
            string NewMemberPassword = "xxxxxxxxxxxxxxx_" + DateTime.Today.ToBinary();
    
            if (SamlResponseCookie != null)
            {
                dynamic SamlResponseCookieValue = JsonConvert.DeserializeObject<dynamic>(HttpUtility.UrlDecode(Request.Cookies["samlresponse"].Value));
    
                if (UserInfoCookie != null)
                {
                    dynamic UserInfoCookieValue = JsonConvert.DeserializeObject<dynamic>(HttpUtility.UrlDecode(Request.Cookies["userinfo"].Value));
    
                    if (UserInfoCookieValue["username"] != string.Empty)
                    {
                        if (!UserStatus.IsLoggedIn)
                        {
                            var CurrentMember = Members.GetByUsername(UserInfoCookieValue["username"].ToString());
    
                            var domainContext = new PrincipalContext(ContextType.Domain, ADDomain, ADPath, ADAdmUsername, ADAdmPassword);
                            ADUser = UserPrincipal.FindByIdentity(domainContext, UserInfoCookieValue["username"].ToString());
    
                            if (CurrentMember == null)
                            {
                                var _newMember = Services.MemberService.CreateMember(ADUser.SamAccountName, UserInfoCookieValue["mail"], ADUser.DisplayName.Trim().ToUpper(), "AFMemberGroup");
                                Services.MemberService.Save(_newMember);
                                Services.MemberService.AssignRole(_newMember.Id, "AFMemberGroup");
                                Services.MemberService.SavePassword(_newMember, NewMemberPassword);
    
                                CurrentMember = Members.GetByUsername(_newMember.Username);
    
                                UpdateMemberDetails(CurrentMember, SamlResponseCookie, UserInfoCookie);
                            }
                            else
                            {
                                if ((CurrentMember.Username != ADUser.SamAccountName) || (CurrentMember.Email != ADUser.UserPrincipalName) || (CurrentMember.Name != ADUser.DisplayName))
                                {
                                    CurrentMember.Username = ADUser.SamAccountName;
                                    CurrentMember.Email = ADUser.UserPrincipalName;
                                    CurrentMember.Name = ADUser.DisplayName;
    
                                    Services.MemberService.Save(CurrentMember);
                                }
                            }
    
                            FormsAuthentication.SetAuthCookie(UserInfoCookieValue["username"], true);
                        }
    
                        return View();
                    }
                    else
                    {
                        Session.Clear();
    
                        UserInfoCookie.Expires = DateTime.Now.AddDays(-1);
    
                        SamlResponseCookie.Expires = DateTime.Now.AddDays(-1);
    
                        if (UserStatus.IsLoggedIn)
                        {
                            FormsAuthentication.SignOut();
                        }
    
                        Response.Redirect(redirectUrl);
                    }
                }
                else
                {
                    Session.Clear();
    
                        UserInfoCookie.Expires = DateTime.Now.AddDays(-1);
    
                        SamlResponseCookie.Expires = DateTime.Now.AddDays(-1);
    
                        if (UserStatus.IsLoggedIn)
                        {
                            FormsAuthentication.SignOut();
                        }
    
                        Response.Redirect(redirectUrl);
                }
            }
            else
            {
                Session.Clear();
    
                UserInfoCookie.Expires = DateTime.Now.AddDays(-1);
    
                SamlResponseCookie.Expires = DateTime.Now.AddDays(-1);
    
                if (UserStatus.IsLoggedIn)
                {
                    FormsAuthentication.SignOut();
                }
    
                Response.Redirect(redirectUrl);
            }
    
            return View();
        }
    
        private void UpdateMemberDetails(IMember CurrentMember, HttpCookie SamlResponseCookie, HttpCookie UserInfoCookieValue)
        {
            ...
        }
    }
    }
    

    With this code, I receive this error:

    'Umbraco.Web.PublishedModels.AFMemberGroup' does not contain a definition for 'Username'
    
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
    
    Exception Details:     Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Umbraco.Web.PublishedModels.AFMemberGroup' does not contain a definition for 'Username'
    
    Source Error:
    
    
    Line 5:     Layout = null;
    Line 6:     
    Line 7:      @Html.Action("CheckSSOAuth","ADFS");
    Line 8:  }
    Line 9:  <!DOCTYPE html>
    
    Source File: C:\inetpub\wwwroot_intranet\Views\ADFSLogin.cshtml    Line: 7
    
    ...
    

    The code that throw the excepton is:

    if ((CurrentMember.Username != ADUser.SamAccountName) || (CurrentMember.Email != ADUser.UserPrincipalName) || (CurrentMember.Name != ADUser.DisplayName))
    
    ...
    

    So I also tried to change this code:

    var CurrentMember = Members.GetByUsername(UserInfoCookieValue["username"].ToString());
    

    with this code (that I safely use in other surface controller):

    var CurrentMember = Services.MemberService.GetByUsername(UserInfoCookieValue["username"].ToString());
    

    but I receive the following error

    'Umbraco.Core.Services.IMemberService' does not contain a definition for 'GetByUsername'
    
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
    
    Exception Details: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Umbraco.Core.Services.IMemberService' does not contain a definition for 'GetByUsername'
    
    Source Error:
    
    
    Line 5:     Layout = null;
    Line 6:     
    Line 7:      @Html.Action("CheckSSOAuth","ADFS");
    Line 8:  }
    Line 9:  <!DOCTYPE html>
    
    Source File: C:\inetpub\wwwroot_intranet\Views\ADFSLogin.cshtml    Line: 7
    
    ...
    
  • Adriano Fabri 459 posts 1602 karma points
    Apr 14, 2021 @ 08:20
    Adriano Fabri
    0

    I also tried using RenderMvcController...but nothing. I have same problems.

    I changed the title of the post, because I don't need to return a bool but to view the page

  • Adriano Fabri 459 posts 1602 karma points
    May 05, 2021 @ 11:04
    Adriano Fabri
    100

    Hi to all and sorry for delay.

    I want to share with you that I found the solution by completely changing my approach.

    My Controller now inherits from UmbracoController

    public class ADFSController : UmbracoController
    

    I created various (static) methods to do all operations and now I can call them directly from views.

    The solution was easier than I thought

    A.

Please Sign in or register to post replies

Write your reply to:

Draft